package com.gxkj.drm.controllers;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.gxkj.drm.dto.CodeMsg;
import com.gxkj.drm.entitys.ResourceManage;
import com.gxkj.drm.enums.SendType;
import com.gxkj.drm.service.ResourceManageService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 资源管理
 * @author shaoxiangfei
 *
 */
@Controller
@RequestMapping(value = "/resource_manage")
public class ResoucesManageController extends BaseController {

    @Resource
    private ResourceManageService resourceManageService;

    private static final Logger logger = LoggerFactory.getLogger(ResoucesManageController.class);

    /**
     * 推送资源属性内容到集群
     * @param request
     * @param cluster
     * @param attribute
     * @param attributeValue
     * @return
     */
   // @Permission(needLogin = false, role = RoleType.USER)
    @ResponseBody
    @RequestMapping(value = "/push_all_attribute", method = { RequestMethod.POST, RequestMethod.GET })
    public CodeMsg pushAllAttributeValue(HttpServletRequest request, @RequestParam(value = "cluster") String cluster,
                                         @RequestParam(value = "attribute") String attribute,
                                         @RequestParam(value = "attributeValue") String attributeValue,
                                         @RequestParam(value = "sendType") int sendType) {
        SendType type = SendType.findSendType(sendType);
        if (type == null) {
            return new CodeMsg(2, "推送属性值失败");
        }

        //0表示全部推送成功，1表示部分推送成功，2表示全部推送失败
        int isFlag = this.resourceManageService.pushAllAttributeValue(cluster, attribute, attributeValue, type);

        String result = isFlag==0?"Success":(isFlag==1?"Partial-success":"Fail");
        String trigger = type.getType()==1?"Restart":(type.getType()==2?"Manual-push":"Third-party");

        if(! type.equals(SendType.THIRD_PARTY)) {
            this.userLog(request, "集群全推", cluster, String.format("Attribute=%s, PushValue=%s, Trigger=%s, Result=%s",
                    attribute, attributeValue, trigger, result));
        } else {
            logger.info(String.format("集群全推, Cluster=%s, Attribute=%s, PushValue=%s, Trigger=%s, Result=%s",
                    cluster, attribute, attributeValue, trigger, result));
        }


        if (isFlag == 0) {
            return CodeMsg.SUCCESS;
        } else if (isFlag == 1) {
            return new CodeMsg(1, "推送部分属性值成功");
        } else {
            return new CodeMsg(2, "推送属性值失败");
        }
    }

    /**
     * 推送资源属性内容到单台机器
     * @param request
     * @param resourceId
     * @param pushValue
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/push_attribute", method = RequestMethod.POST)
    public CodeMsg pushAttributeValue(HttpServletRequest request, @RequestParam(value = "resourceId") long resourceId,
                                      @RequestParam(value = "pushValue") String pushValue) {
        String currentValue = request.getParameter("currentValue");
        String attribute = request.getParameter("attribute");
        String cluster = request.getParameter("cluster");
        String instance = request.getParameter("instance");
        boolean isSuccess = this.resourceManageService.pushAttributeValue(resourceId, pushValue);
        String result = isSuccess?"Success":"Fail";
        this.userLog(request, "单台推送", cluster,
                String.format("Attribute=%s, currentValue=%s, PushValue=%s, Instance=%s, Result=%s", attribute, currentValue, pushValue, instance, result));

        if (isSuccess) {
            return CodeMsg.SUCCESS;
        } else {
            return CodeMsg.ERROR;
        }

    }

    /**
     * 根据cluster、ip移除指定的push服务
     * @param request
     * @param clusterValue
     * @param ipValue
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/remove_ip_service", method = RequestMethod.POST)
    public CodeMsg removeIpService(HttpServletRequest request, @RequestParam(value = "clusterValue") String clusterValue,
                                   @RequestParam(value = "ipValue") String ipValue) {
        boolean isSuccess = this.resourceManageService.dealResourceManageInfo(clusterValue, ipValue, null);

        this.userLog(request, "移除实例", clusterValue,
                String.format("Cluster=%s, Instance=%s, Result=%s", clusterValue, ipValue, isSuccess?"Success":"Fail"));

        if (isSuccess) {
            return CodeMsg.SUCCESS;
        } else {
            return CodeMsg.ERROR;
        }

    }

    /**
     * 接受目标主机推送过来的初始化资源属性值
     * @param pushData
     * @return
     */
   // @Permission(needLogin = false)
    @ResponseBody
    @RequestMapping(value = "/push_resource", method = RequestMethod.POST)
    public CodeMsg pushResource(@RequestParam(value = "push_data") String pushData) {
        try {
            if (StringUtils.isNotEmpty(pushData)) {
                JSONObject json = JSONObject.parseObject(pushData);
                String ip = json.getString("ip");
                String cluster = json.getString("cluster");
                List<ResourceManage> list = JSON.parseObject(json.getString("data"),
                        new TypeReference<ArrayList<ResourceManage>>() {
                        });
                //处理资源
                this.resourceManageService.dealResourceManageInfo(cluster, ip, list);
            }

            logger.info(String.format("推送资源信息成功,pushData=%s", pushData));
        } catch (Exception e) {
            logger.error(String.format("推送资源信息失败,pushData=%s", pushData), e);
        }

        return CodeMsg.SUCCESS;
    }
}
